package org.mozhu.mboot.core.template.simple;

import java.util.Map;

import com.google.common.collect.Maps;
import org.mozhu.mboot.core.template.TemplateRender;

public class SimpleTemplateRender implements TemplateRender {

	@Override
	public String render(String template, Map<String, Object> model) {
		Map<String, String> flatMap = traverseMap(model);
		return replaceTemplate(template, flatMap);
	}

	private String replaceTemplate(String template, Map<String, String> flatMap) {
		for (Map.Entry<String, String> entry : flatMap.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			template = template.replace(key, value);
		}
		return template;
	}

	public Map<String, String> traverseMap(Map<String, Object> assembleContext) {
		return getKeyForMap(null, assembleContext);
	}

	@SuppressWarnings("unchecked")
	private Map<String, String> getKeyForMap(String keyChain, Map<String, Object> iteratorMap) {
		Map<String, String> resultMap = Maps.newHashMap();
		for (Map.Entry<String, Object> entry : iteratorMap.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();
			String simplekeyStr = keyChain != null ? keyChain + "." + key : "${" + key;
			String variouskeyStr = keyChain != null ? keyChain + "['" + key + "']" : "${" + key;
			if (value instanceof Map) {
				resultMap.putAll(getKeyForMap(simplekeyStr, (Map<String, Object>) value));
				resultMap.putAll(getKeyForMap(variouskeyStr, (Map<String, Object>) value));
			} else {
				resultMap.put(variouskeyStr + "}", value.toString());
				resultMap.put(simplekeyStr + "}", value.toString());
			}
		}
		return resultMap;
	}

}
